package com.silverhaze.diamond.client.ui.table;

import com.silverhaze.diamond.common.entity.Service;
import com.silverhaze.diamond.client.ui.dialogs.view.ViewDialog;
import com.silverhaze.diamond.client.ui.table.model.ServiceTableModel;
import com.silverhaze.diamond.client.ui.table.renderers.ServiceTableRenderer;
import com.silverhaze.diamond.client.ui.table.shells.ServiceShell;

import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Comparator;

/**
 * SystemUser: Babanin
 * Date: 03.07.2008
 * Time: 23:55:35
 */
public class ServiceTable extends AbstractServiceTable {
    public ServiceTable() {
        initialize();
    }

    public ServiceTable(TableModel dm) {
        super(dm);

        initialize();
    }

    private void initialize() {
        setAutoCreateRowSorter(true);

        for (int i = 0; i < getColumnCount(); i++) {
            ((TableRowSorter) getRowSorter()).setComparator(i, new Comparator<Object>() {
                public int compare(Object o1, Object o2) {
                    return ((ServiceShell) o1).compareTo(o2);
                }
            });
        }

        setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        initializeColumnWidth();

        getModel().addTableModelListener(new TableModelListener() {
            public void tableChanged(TableModelEvent e) {
                initializeColumnWidth();
            }
        });

        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() >= 2) {
                    Service service = ((ServiceTableModel) getModel()).getObjectAtRow(getSelectedRow());
                    ViewDialog.service(service);
                }
            }
        });

        setDefaultRenderer(Object.class, new ServiceTableRenderer());
        setGridColor(Color.GRAY);
    }

    private void initializeColumnWidth() {
    }
}